<template>
  <div class="container">
    <!-- 播放器 -->
    <video class="demo-video" ref="videoRef" muted autoplay controls disablepictureinpicture
      controlsList="nodownload"></video>
  </div>
</template>
<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue';
import flvjs from "flv.js";
import { useRoute } from 'vue-router';
// 当前流地址
let props = defineProps({
  url: {
    type: String,
    default: null
  },
  ifContinue: {
    type: Number,
    default: 1
  },
  id: {
    type: Number,
    default: 0
  }
})
// flv
let player = ref(null);
// 播放器dom
let videoRef = ref();
// 播放加载标记
let stoped = ref(false)
let route = useRoute()

// 换源
const selectSource = () => {
  distroySource()
  loadSource()
}

watch(props,()=>{
  selectSource()
})


// 加载数据
const loadSource = () => {
  if(props.url==""||props.url==null) return
  if (flvjs.isSupported()) {
    let video = videoRef.value;
    if (video) {
      try {
        player.value = flvjs.createPlayer({
          type: "flv",
          isLive: true,
          url: `ws://120.76.201.36:8889/rtsp/${props.id}/?url=${props.url}`
        });
        player.value.attachMediaElement(video);
        player.value.load();
        player.value.play();
      } catch (error) {
        console.error("Error creating or playing the player:", error);
      }
    } else {
      console.warn("Video element not found in the DOM.");
    }
  } else {
    console.warn("FLV.js is not supported in this environment.");
  }
}

const distroySource = () => {
  if (player.value) {
    try {
      player.value.destroy();
    } catch (error) {
      console.error("Error destroying the player:", error);
    }
  }
}


onMounted(() => {
  console.log(props.url)
  if (route.query?.continue) {
    ifContinue.value = route.query.continue
  }
  loadSource()
  const video = document.querySelector("video");
  if (props.ifContinue == 1) {
    video.addEventListener("play", (event) => {
      if (stoped.value) {
        selectSource()
        stoped.value = false
      }
    });
    video.addEventListener("pause", (event) => {
      if (document.visibilityState != 'hidden') {
        stoped.value = true
      }
      else video.play()
    });
  }
});

onBeforeUnmount(() => {
  distroySource()
});
</script>
<style scoped>
.container {
  background-color: black;
  width: 100%;
  height: 100%;
  display: flex;
  box-sizing: border-box;
  overflow: hidden;

  .demo-video {
    flex:1;
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    border: none;
    object-fit: cover;
  }
}
</style>
